package com.smec.moblie.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.hardware.Camera;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.smec.moblie.R;
import com.smec.moblie.adapter.MaintenancePhotoJobitemAdapter;
import com.smec.moblie.adapter.MemoAdapter;
import com.smec.moblie.adapter.MntjobElvAdapter;
import com.smec.moblie.bean.Gps;
import com.smec.moblie.bean.MaintenanceBean;
import com.smec.moblie.bean.MaintenanceDetailBean;
import com.smec.moblie.bean.MaintenanceFastrepairhisBean;
import com.smec.moblie.bean.MaintenanceMemoBean;
import com.smec.moblie.bean.MaintenancePhotoBean;
import com.smec.moblie.bean.MaintenancePhotoJobitemBean;
import com.smec.moblie.bean.MntjobChildren;
import com.smec.moblie.bean.Mntjobitem;
import com.smec.moblie.bean.Mntjobtemplate;
import com.smec.moblie.bean.Mntjobtpldetail;
import com.smec.moblie.common.ConstValue;
import com.smec.moblie.control.EventCenter;
import com.smec.moblie.control.MainControl;
import com.smec.moblie.control.PublicControl;
import com.smec.moblie.crash.ExitAppUtils;
import com.smec.moblie.location.ServiceUtil;
import com.smec.moblie.service.MntJobService;
import com.smec.moblie.util.ConfigContext;
import com.smec.moblie.util.Util;
import com.smec.moblie.util.imageuploader.FndResource;
import com.smec.moblie.util.imageuploader.ResourceFacade;
import com.smec.moblie.view.RippleView;
import com.smec.moblie.widget.MainDetailListView;
import com.smec.moblie.widget.MntjobExpandableListView;

import net.frakbot.jumpingbeans.JumpingBeans;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/***
 * 工单详情页
 */
public class MainDetailActivity extends BaseActivity implements ConstValue {
    /**
     * 返回按钮
     **/
    private ImageView imageview_back;
    private RippleView rippleView_customer;//客户信息水波
    /**
     * 选中列表页项
     **/
    private MaintenanceBean maintenanceBean;
    /**
     * 详情类
     **/
    private MaintenanceDetailBean maintenanceDetailBean;
    /**
     * 工单id
     **/
    private String workorderid = "";
    /**
     * 梯id
     **/
    private String eleid = "";
    /**
     * 作业计划ID 来查询工单对应  项
     */
    private String jobschid = "";
    /**
     * 工单编号
     */
    private TextView workordernoTv;
    /**
     * 楼宇名
     */
    private TextView buildingnameTv;
    /**
     * 安装 地址
     */
    private TextView locaddressTv;
    /**
     * 客户名
     */
    private TextView customernameTv;
    /**
     * 合同号梯号
     */
    private TextView elecontractnoTv;
    /**
     * 保养人
     */
    private TextView staffnameTv;
    /**
     * 保养日期
     */
    private TextView mntschdateTv;
    /**
     * 出发时间
     */
    private TextView departuredateTv;

    /**
     * 到达时间
     */
    private TextView onsitedateTv;
    /**
     * 作业包列表
     */
    private MntjobExpandableListView mntjobElv;

    /**
     * 急修历史
     **/
    private TextView textView_fastrepairHis;

    /**
     * 合同号梯号
     **/
    private RippleView rippleView_contract;
    /**
     * 急修历史
     **/
    private RippleView rippleView_fastrepairhis;
    /**
     * 保养广播通
     **/
    private RippleView rippleView_remesNotice;
    /**
     * 近期保养遗 问题
     **/
    private RippleView rippleView_history_problem;

    private ImageView imageview_ele_remes;

    private ImageView imageView_light;
    /***
     * 作业包列表适配器
     */
    private MntjobElvAdapter mMntjobElvAdapter;
    private List<String> parent = new ArrayList<String>();
    private Map<String, List<String>> map = new HashMap<String, List<String>>();
    private ArrayList<MntjobChildren> mntjobChildrenList = new ArrayList<MntjobChildren>();
    private JumpingBeans jumpingBeans;
    /**
     * 作业包
     */
    private List<Mntjobtemplate> mntjobtemplateList;
    private List<Mntjobtpldetail> Mntjobtpldetail;
    private List<Mntjobitem> mntjobitems = new ArrayList<Mntjobitem>();
    private TextView mntjobtemplateTv;
    private ArrayList<List<MntjobChildren>> mntjobChildrensList = new ArrayList<List<MntjobChildren>>();
    /***
     * 列表项
     */
    private MainDetailListView maintenancePhotoJobitemLv;
    private ArrayList<MaintenancePhotoJobitemBean> maintenancePhotoJobitemBeanList = new ArrayList<MaintenancePhotoJobitemBean>();
    private MaintenancePhotoJobitemAdapter maintenancePhotoJobitemAdapter;
    private RelativeLayout layout_takeOrderPicture;
    private RelativeLayout layout_takeScenePicture;
    private ImageView imageView_takeOrderPicture;
    private TextView textView_takeScenePicture;
    private String photoName;
    private ArrayList<MaintenancePhotoBean> maintenancePhotoBeanSceneList = new ArrayList<MaintenancePhotoBean>();
    /***
     * 梯备忘
     */
    private MainDetailListView listView_memo;
    private TextView textView_addMemo;
    private MemoAdapter memoAdapter;
    private ArrayList<MaintenanceMemoBean> maintenanceMemoBeanList = new ArrayList<MaintenanceMemoBean>();
    /***
     * 开始出发按钮
     */
    private Button button_submit;

    /**
     * 工单备
     */
    private EditText editText_workorder_description;
    /**************************
     * 其他
     **************************/
    public static final String MNTJOBSERVICE_RESULT = "com.smec.moblie.service.MntJobService.RESULT";

    private int CAMERA_ACTIVITY_REQUEST = 1023;//工作项拍照
    private int CAMERA_ORDER_PICTURE = 10024;//工单照拍照
    private int CAMERA_ACTION_PICTURE = 10025;//场景照
    /**
     * 拍 项选中项
     **/
    private int cameratemp = 0;
    /**
     * 急修历史总数
     **/
    private int fastrepairHiscount = 0;

    private String lo;//坐标经度
    private String la;//坐标纬度

    private int listPosition;//list position

    private Dialog dialog;//挡板

    /****
     * 上传提
     ****/
    private SVProgressHUD pd = null;

    private DisplayImageOptions options;
    /**
     * 子围栏中心经度
     **/
    private double longitude;
    /**
     * 子围栏中心纬度
     **/
    private double latitude;

    /**
     * 手   机控制
     */
    private Camera mycamera = null;

    private int level;// 电量

    private RelativeLayout rl_title;

    private BroadcastReceiver mntjobReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {


            if (intent.getAction() == MNTJOBSERVICE_RESULT) {
                parent = new ArrayList<String>();
                map = new HashMap<String, List<String>>();
                String templateid = maintenanceBean.getTemplate_id();
                mntjobtemplateList = DataSupport.where("template_id = ?", templateid).find(Mntjobtemplate.class);
                mntjobtemplateTv.setText(Util.conversionStr(mntjobtemplateList.get(0).getTemplate_name()));
                Cursor cursor = DataSupport.findBySQL("select distinct jobitem_category_code, meaning from Mntjobitem i join Mntjobtpldetail t on i.job_item_id = t.job_item_id  where template_id = ? order by jobitem_category_code", templateid);
                while (cursor.moveToNext()) {
                    int meaningColumnIndex = cursor.getColumnIndex("meaning");
                    String meaning = cursor.getString(meaningColumnIndex);
                    parent.add(meaning);
                }
                Cursor cursor1 = DataSupport.findBySQL("select job_no,job_name,meaning from Mntjobitem i join Mntjobtpldetail d   on i.job_item_id = d.job_item_id where d.template_id = ? order by i.item_no,i.job_no asc", templateid);

                while (cursor1.moveToNext()) {
                    MntjobChildren mMntjobChildren = new MntjobChildren();
                    int jobnoColumnIndex = cursor1.getColumnIndex("job_no");
                    String jobno = cursor1.getString(jobnoColumnIndex);
                    mMntjobChildren.setJob_no(jobno);
                    int jobnameColumnIndexColumnIndex = cursor1.getColumnIndex("job_name");
                    String jobname = cursor1.getString(jobnameColumnIndexColumnIndex);
                    mMntjobChildren.setJob_name(jobname);
                    int meaningColumnIndex = cursor1.getColumnIndex("meaning");
                    String meaning = cursor1.getString(meaningColumnIndex);
                    mMntjobChildren.setMeaning(meaning);
                    mntjobChildrenList.add(mMntjobChildren);
                }
                DataSupport.deleteAll(MntjobChildren.class);
                DataSupport.saveAll(mntjobChildrenList);
                for (String p : parent) {
                    List<MntjobChildren> mntjobChildren = DataSupport.where("meaning = ?", p).find(MntjobChildren.class);
                    List<String> child = new ArrayList<String>();
                    for (int i = 0; i < mntjobChildren.size(); i++) {
                        child.add(mntjobChildren.get(i).getJob_no() + " " + mntjobChildren.get(i).getJob_name());
                    }
                    map.put(p, child);
                }
                mMntjobElvAdapter.setMntjobElvList(parent, map);
                jumpingBeans.stopJumping();

            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == (CAMERA_ACTIVITY_REQUEST + cameratemp)) {//拍照项返回
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;
                Bitmap saveBitmap = BitmapFactory.decodeFile(imgPath + photoName + ".jpeg", options);
                try {
                    PublicControl.saveFile(saveBitmap, imgPath + photoName + ".jpeg");// 把压缩的图片保存到本地
                    maintenancePhotoJobitemBeanList.get(cameratemp).setAction_type_result(photoName);
                    ContentValues values = new ContentValues();
                    values.put("action_type_result", photoName);
                    int changeRow = DataSupport.updateAll(MaintenancePhotoJobitemBean.class, values, "job_sch_list_id = ?", maintenancePhotoJobitemBeanList.get(cameratemp).getJob_sch_list_id());
                    if (changeRow == 0) {
                        Toast.makeText(this, "照片保存失败，请重新拍摄", Toast.LENGTH_LONG).show();
                    }
                    maintenancePhotoJobitemAdapter.setListData(maintenancePhotoJobitemBeanList);
                    FndResource fndResource = new FndResource(photoName, photoName, "image/jpeg", 0);
                    fndResource.save();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == CAMERA_ORDER_PICTURE) {//工单照返回
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;
                Bitmap saveBitmap = BitmapFactory.decodeFile(imgPath + photoName + ".jpeg", options);
                try {
                    PublicControl.saveFile(saveBitmap, imgPath + photoName + ".jpeg");// 把压缩的图片保存到本地
                    imageView_takeOrderPicture.setImageBitmap(saveBitmap);
                    ArrayList<MaintenancePhotoBean> maintenancePhotoBeanList = (ArrayList<MaintenancePhotoBean>) DataSupport.where("workorder_id = ? AND object_status_code = 'VALID' AND item_type_code = 'WORKORDER_IMG'", workorderid).find(MaintenancePhotoBean.class);
                    if (maintenancePhotoBeanList.size() > 0) {
                        for (MaintenancePhotoBean maintenancePhotoBean : maintenancePhotoBeanList) {
                            MaintenancePhotoBean maintenancePhotoBeanTemp = new MaintenancePhotoBean();
                            maintenancePhotoBeanTemp.setObject_status_code("INVALID");
                            maintenancePhotoBeanTemp.update(maintenancePhotoBean.getId());
                        }
                    }

                    createPhoto("WORKORDER_IMG");

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == CAMERA_ACTION_PICTURE) {//场景照返回
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;
                Bitmap saveBitmap = BitmapFactory.decodeFile(imgPath + photoName + ".jpeg", options);
                try {
                    PublicControl.saveFile(saveBitmap, imgPath + photoName + ".jpeg");// 把压缩的图片保存到本地
                    maintenancePhotoBeanSceneList.add(createPhoto("ADDITIONAL_IMG"));
                    textView_takeScenePicture.setText("已拍" + maintenancePhotoBeanSceneList.size() + "张");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == CAMERA_DANGBAN) {
                dialog.dismiss();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 创建工单 和场景
     *
     * @param item_type_code
     */
    private MaintenancePhotoBean createPhoto(String item_type_code) {
        MaintenancePhotoBean maintenancePhotoBean = new MaintenancePhotoBean();
        maintenancePhotoBean.setObject_status_code("VALID");
        maintenancePhotoBean.setItem_type_code(item_type_code);
        maintenancePhotoBean.setAssignee(MainActivity.USERNAME);
        maintenancePhotoBean.setResource_id(photoName);
        maintenancePhotoBean.setRecord_time(Util.getSystemDateNow());
        maintenancePhotoBean.setWorkorder_id(workorderid);
        maintenancePhotoBean.setResource_list_id(UUID.randomUUID().toString());
        maintenancePhotoBean.save();
        FndResource fndResource = new FndResource(photoName, photoName, "image/jpeg", 0);
        fndResource.save();
        return maintenancePhotoBean;
    }

    @Override
    protected void getData() {
        registerReceiver();
        MntJobService.startMntJobService(this);
        workorderid = maintenanceBean.getWorkorder_id();
        eleid = maintenanceBean.getEle_id();
        jobschid = maintenanceBean.getJob_sch_id();

        mMntjobElvAdapter = new MntjobElvAdapter(this);
        maintenancePhotoJobitemAdapter = new MaintenancePhotoJobitemAdapter(this);
        maintenancePhotoJobitemLv.setAdapter(maintenancePhotoJobitemAdapter);
        maintenancePhotoJobitemAdapter.setListData(maintenancePhotoJobitemBeanList);
        mntjobElv.setAdapter(mMntjobElvAdapter);
        mMntjobElvAdapter.setMntjobElvList(parent, map);
        mntjobElv.setGroupIndicator(null);
        new getMainListForDb().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        maintenancePhotoJobitemLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final MaintenancePhotoJobitemBean maintenancePhotoJobitemBean = maintenancePhotoJobitemBeanList.get(position);
                cameratemp = position;
                if (!maintenanceBean.getWo_status_code().equals("COMPLETED") && maintenanceBean.getOrderCode() > ORDER_ARRIVE) {
                    if ("".equals(maintenancePhotoJobitemBean.getAction_type_result())) {
                        takePhoto(CAMERA_ACTIVITY_REQUEST + cameratemp);
                    } else {
                        new AlertView("提示", null, "取消", null, new String[]{"拍照", "显示图片"}, MainDetailActivity.this, AlertView.Style.ActionSheet, new OnItemClickListener() {
                            @Override
                            public void onItemClick(Object o, int position) {
                                if (position == 0) {
                                    takePhoto(CAMERA_ACTIVITY_REQUEST + cameratemp);
                                } else if (position == 1) {
                                    File filetemp = imageLoader.getDiscCache().get(SERVER_BASE_PATH + "rest/resources/" + maintenancePhotoJobitemBean.getAction_type_result());
                                    if (filetemp.exists()) {
                                        showPhoto(filetemp.getPath());

                                    } else {
                                        showPhoto(imgPath + maintenancePhotoJobitemBean.getAction_type_result() + ".jpeg");
                                    }
                                }
                            }
                        }).show();
                    }
                } else if (maintenanceBean.getOrderCode() <= ORDER_ARRIVE) {
                    Toast.makeText(MainDetailActivity.this, "未到现场，还无法拍照", Toast.LENGTH_SHORT).show();
                } else if (maintenanceBean.getWo_status_code().equals("COMPLETED")) {

                    if (!maintenancePhotoJobitemBean.getAction_type_result().equals("")) {
                        File filetemp = imageLoader.getDiscCache().get(SERVER_BASE_PATH + "rest/resources/" + maintenancePhotoJobitemBean.getAction_type_result());
                        if (filetemp.exists()) {
                            showPhoto(filetemp.getPath());
                        } else {
                            showPhoto(imgPath + maintenancePhotoJobitemBean.getAction_type_result() + ".jpeg");
                        }
                    }
                }
            }
        });


    }


    /***
     * 获取详情页和列表页 缓存数据
     * 列表项
     */
    private class getMainListForDb extends AsyncTask<Void, Void, Void> {
        ArrayList<MaintenancePhotoBean> maintenancePhotoBeanList = new ArrayList<MaintenancePhotoBean>();
        boolean isOK = true;

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if (!isOK) {
                Toast.makeText(MainDetailActivity.this, "加载数据失败，请在列表页下拉刷新", Toast.LENGTH_SHORT).show();
                MainDetailActivity.this.finish();
            } else {
                if (null == maintenanceDetailBean) {
                    Toast.makeText(MainDetailActivity.this, "加载电梯数据失败，请在列表页下拉刷新", Toast.LENGTH_LONG).show();
                    MainDetailActivity.this.finish();
                } else {
                    workordernoTv.setText(maintenanceBean.getWorkorder_no().toString());
                    buildingnameTv.setText(maintenanceBean.getBUILDING_NAME().toString());
                    locaddressTv.setText(maintenanceBean.getLoc_address().toString());
                    customernameTv.setText(maintenanceBean.getCustomer_name().toString());
                    elecontractnoTv.setText(maintenanceBean.getELE_CONTRACT_NO().toString());
                    staffnameTv.setText(maintenanceBean.getStaffname().toString());
                    mntschdateTv.setText(Util.generateSchTime(maintenanceBean.getMNT_SCH_DATE().toString(), maintenanceBean.getMNT_TIMERANGE_CODE()));
                    textView_fastrepairHis.setText("急修历史查询(" + fastrepairHiscount + ")");
                    String departure_date = maintenanceBean.getDeparture_date();
                    if ("".equals(departure_date)) {
                        departuredateTv.setText("未出发");
                        departuredateTv.setTextColor(Color.RED);
                    } else {
                        departuredateTv.setText(departure_date);
                        departuredateTv.setTextColor(Color.BLACK);
                    }
                    String onsite_date = maintenanceBean.getOnsite_date().toString();
                    if ("".equals(onsite_date)) {
                        onsitedateTv.setText("未到达");
                        onsitedateTv.setTextColor(Color.RED);
                    } else {
                        onsitedateTv.setText(onsite_date);
                        onsitedateTv.setTextColor(Color.BLACK);
                    }
                    if (maintenancePhotoBeanSceneList.size() > 0) {
                        textView_takeScenePicture.setText("已拍" + maintenancePhotoBeanSceneList.size() + "张");
                    } else {
                        textView_takeScenePicture.setText("未拍照片");
                    }
                    maintenancePhotoJobitemAdapter.setListData(maintenancePhotoJobitemBeanList);
                    editText_workorder_description.setText(maintenanceBean.getWorkorder_description());
                    //设置电梯备忘
                    memoAdapter.setList(maintenanceMemoBeanList, maintenanceBean.getOrderCode());

                    if (maintenancePhotoBeanList.size() > 0) {
                        imageView_takeOrderPicture.setBackgroundColor(Color.parseColor("#00FFFFFF"));
                        options = new DisplayImageOptions.Builder().showStubImage(R.mipmap.photo).showImageForEmptyUri(R.mipmap.photo).showImageOnFail(R.mipmap.photo)
                                .cacheInMemory(true).cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
                                .build();
                        MaintenancePhotoBean maintenancePhotoBean = maintenancePhotoBeanList.get(0);
                        File file = new File(imgPath + maintenancePhotoBean.getResource_id() + ".jpeg");

                        if (file.exists()) {
                            imageLoader.displayImage("file://" + imgPath + maintenancePhotoBean.getResource_id() + ".jpeg", imageView_takeOrderPicture, options);
                        } else {
                            imageLoader.displayImage(SERVER_BASE_PATH + "rest/resources/" + maintenancePhotoBean.getResource_id(), imageView_takeOrderPicture, options);
                        }
                    }

                    if (maintenanceBean.getOrderCode() == ORDER_STARTOFF) {
                        button_submit.setText("开始出发");
                    } else if (maintenanceBean.getOrderCode() == ORDER_ARRIVE) {
                        button_submit.setText("到达现场");
                    } else if (maintenanceBean.getOrderCode() == ORDER_SUBMITINFORMATION) {
                        button_submit.setText("离开并提交");
                    } else if (maintenanceBean.getOrderCode() == ORDER_SUBMIT_WITHOUT_IMAGE) {
                        button_submit.setText("照片补传");
                    } else if (maintenanceBean.getOrderCode() == ORDER_STATION_REJECT) {
                        button_submit.setText("驳回重新提交");
                    }
                    try {
                        longitude = Double.parseDouble(maintenanceBean.getLongitude());
                        latitude = Double.parseDouble(maintenanceBean.getLatitude());
                    } catch (Exception e) {
                        longitude = 0;
                        latitude = 0;
                    }

                    if (null != maintenanceDetailBean.getMONITOR_STATUS_CODE() && "1".equals(maintenanceDetailBean.getMONITOR_STATUS_CODE())) {
                        imageview_ele_remes.setVisibility(View.VISIBLE);
                    } else {
                        imageview_ele_remes.setVisibility(View.GONE);
                    }
                }
            }
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                maintenanceDetailBean = ((ArrayList<MaintenanceDetailBean>) DataSupport.where("ELE_ID = ?", eleid).find(MaintenanceDetailBean.class)).get(0);
//                maintenancePhotoJobitemBeanList.addAll(DataSupport.where("job_sch_id = ? AND job_item_sch_code = 'Y'", jobschid).find(MaintenancePhotoJobitemBean.class));//照片列表项
                Cursor cursor = DataSupport.findBySQL("select distinct assignee,job_sch_list_id,job_sch_id,job_item_id,item_no,job_item_sch_code,action_type_result,lookup_code,meaning,action_type_code,job_no,job_name from MaintenancePhotoJobitemBean  where job_sch_id = ? AND job_item_sch_code = 'Y'", jobschid);
                while (cursor.moveToNext()) {
                    MaintenancePhotoJobitemBean photoJobitemBean = new MaintenancePhotoJobitemBean();
                    photoJobitemBean.setAssignee(cursor.getString(cursor.getColumnIndex("assignee")));
                    photoJobitemBean.setJob_sch_list_id(cursor.getString(cursor.getColumnIndex("job_sch_list_id")));
                    photoJobitemBean.setJob_sch_id(cursor.getString(cursor.getColumnIndex("job_sch_id")));
                    photoJobitemBean.setJob_item_id(cursor.getString(cursor.getColumnIndex("job_item_id")));
                    photoJobitemBean.setItem_no(cursor.getString(cursor.getColumnIndex("item_no")));
                    photoJobitemBean.setJob_item_sch_code(cursor.getString(cursor.getColumnIndex("job_item_sch_code")));
                    photoJobitemBean.setAction_type_result(cursor.getString(cursor.getColumnIndex("action_type_result")));
                    photoJobitemBean.setLookup_code(cursor.getString(cursor.getColumnIndex("lookup_code")));
                    photoJobitemBean.setMeaning(cursor.getString(cursor.getColumnIndex("meaning")));
                    photoJobitemBean.setAction_type_code(cursor.getString(cursor.getColumnIndex("action_type_code")));
                    photoJobitemBean.setJob_no(cursor.getString(cursor.getColumnIndex("job_no")));
                    photoJobitemBean.setJob_name(cursor.getString(cursor.getColumnIndex("job_name")));

                    maintenancePhotoJobitemBeanList.add(photoJobitemBean);
                }
                maintenanceMemoBeanList.addAll(DataSupport.where("ele_id = ? AND memo_status_code = 'PROCESSING'", eleid).find(MaintenanceMemoBean.class));
                fastrepairHiscount = DataSupport.where("ele_id = ?", eleid).count(MaintenanceFastrepairhisBean.class);
                maintenancePhotoBeanSceneList.addAll(DataSupport.where("workorder_id = ? AND object_status_code = 'VALID' AND item_type_code = 'ADDITIONAL_IMG'", workorderid).find(MaintenancePhotoBean.class));
                maintenancePhotoBeanList = (ArrayList<MaintenancePhotoBean>) DataSupport.where("workorder_id = ? AND object_status_code = 'VALID' AND item_type_code = 'WORKORDER_IMG'", workorderid).find(MaintenancePhotoBean.class);
            } catch (Exception e) {
                e.getMessage();
                isOK = false;
            }
            return null;
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //手电筒
            case R.id.imageView_light:
                if (null == mycamera) {
                    try {
                        mycamera = Camera.open();
                        OpenLight();

                    } catch (Exception e) {
                        Log.e("debug", "Camera Open erro:" + e.getMessage());
                    }

                } else {
                    CloseLight();
                }
                break;
            //返回按钮
            case R.id.imageview_back:
                MainDetailActivity.this.finish();
                break;
            //添加备忘
            case R.id.textView_addMemo:
                MaintenanceMemoBean maintenanceMemoBean = new MaintenanceMemoBean();
                maintenanceMemoBean.setEle_id(eleid);
                maintenanceMemoBean.setEle_memo_id(UUID.randomUUID().toString());
                maintenanceMemoBean.setAssignee(MainActivity.USERNAME);
                maintenanceMemoBeanList.add(maintenanceMemoBean);
                maintenanceMemoBean.save();
                memoAdapter.setList(maintenanceMemoBeanList, maintenanceBean.getOrderCode());
                break;
            //提交按钮
            case R.id.button_submit:

                //获取当前坐标
                SharedPreferences mapPreferences = getSharedPreferences("SmecMntMapService",
                        Context.MODE_PRIVATE);
                lo = mapPreferences.getString("lon", "未成功获取");
                la = mapPreferences.getString("lat", "未成功获取");
                String locationName = mapPreferences.getString("LocationName", "未成功获取");


                if (maintenanceBean.getOrderCode() == ORDER_ARRIVE) {
                    try {
//                        Boolean isArrived = ServiceUtil.getCachelocation(MainDetailActivity.this, longitude + "", latitude + "");
                        Boolean isArrived = false;
                        Boolean isNO_COORDINATE = false;
                        if (longitude != 0 && latitude != 0) {
                            isArrived = ServiceUtil.getCachelocation(MainDetailActivity.this, longitude + "", latitude + "");

                        } else {
                            isArrived = true;
                            maintenanceBean.setArrive_status(NO_COORDINATE);
                            maintenanceBean.setIsDirty(1);
                            maintenanceBean.update(maintenanceBean.getId());
                            MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
                            maintenanceBeanTemp.setArrive_status(NO_COORDINATE);
                            maintenanceBeanTemp.setIsDirty(1);

                            maintenanceBeanTemp.update(maintenanceBean.getId());
                            isNO_COORDINATE = true;
//                            Toast.makeText(this, "", Toast.LENGTH_LONG).show();
                        }
                        if (!isArrived) {
                            Intent intent = new Intent(
                                    MainDetailActivity.this,
                                    ElectronicFenceMapActivity.class);
                            intent.putExtra("longitude", longitude);
                            intent.putExtra("latitude", latitude);
                            intent.putExtra("position", -1);
                            startActivity(intent);
                        } else {
                            String toastString = "";
                            if (isNO_COORDINATE) {
                                toastString = "\n\n当前电梯没有项目坐标，请通知站长维护(工单流程不受此影响，请继续操作)";
                            } else {
                                toastString = "\n\n成功到达现场";
                            }
                            new AlertView("提示", "\n当前地址：" + locationName + toastString, "取消", new String[]{"确定"}, null, MainDetailActivity.this,
                                    AlertView.Style.Alert, new OnItemClickListener() {
                                @Override
                                public void onItemClick(Object o, int p) {
                                    if (p == 0) {
                                        new SubmitAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                    }
                                }
                            }).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (maintenanceBean.getOrderCode() == ORDER_STARTOFF) {
                    new AlertView("提示", "\n    确定开始出发？", "取消", new String[]{"确定"}, null, MainDetailActivity.this,
                            AlertView.Style.Alert, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int p) {
                            if (p == 0) {
                                new SubmitAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                            }
                        }
                    }).show();
                } else {
                    new AlertView("提示", "\n当前地址：" + locationName, "取消", new String[]{"确定"}, null, MainDetailActivity.this,
                            AlertView.Style.Alert, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int p) {
                            if (p == 0) {
                                new SubmitAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                            }
                        }
                    }).show();
                }

                break;
            //工单照拍照
            case R.id.layout_takeOrderPicture:
                final ArrayList<MaintenancePhotoBean> maintenancePhotoBeanList = (ArrayList<MaintenancePhotoBean>) DataSupport.where("workorder_id = ? AND object_status_code = 'VALID' AND item_type_code = 'WORKORDER_IMG'", workorderid).find(MaintenancePhotoBean.class);

                if ("COMPLETED".equals(maintenanceBean.getWo_status_code())) {
                    if (maintenancePhotoBeanList.size() > 0) {
                        MaintenancePhotoBean maintenancePhotoBean = maintenancePhotoBeanList.get(0);
                        File filetemp = imageLoader.getDiscCache().get(SERVER_BASE_PATH + "rest/resources/" + maintenancePhotoBean.getResource_id());
                        if (filetemp.exists()) {
                            showPhoto(filetemp.getPath());
                        } else {
                            showPhoto(imgPath + maintenancePhotoBean.getResource_id() + ".jpeg");
                        }
                    }
                } else {
                    if (maintenanceBean.getOrderCode() <= ORDER_ARRIVE) {
                        Toast.makeText(this, "未到现场，无法拍照", Toast.LENGTH_SHORT).show();
                    } else if (maintenanceBean.getOrderCode() >= ORDER_SUBMITINFORMATION) {
                        if (maintenancePhotoBeanList.size() > 0) {
                            new AlertView("提示", null, "取消", null, new String[]{"拍照", "显示图片"}, this, AlertView.Style.ActionSheet, new OnItemClickListener() {
                                @Override
                                public void onItemClick(Object o, int position) {
                                    if (position == 0) {
                                        takePhoto(CAMERA_ORDER_PICTURE);
                                    } else if (position == 1) {
                                        MaintenancePhotoBean maintenancePhotoBean = maintenancePhotoBeanList.get(0);
                                        File filetemp = imageLoader.getDiscCache().get(SERVER_BASE_PATH + "rest/resources/" + maintenancePhotoBean.getResource_id());
                                        if (filetemp.exists()) {
                                            showPhoto(filetemp.getPath());
                                        } else {
                                            showPhoto(imgPath + maintenancePhotoBean.getResource_id() + ".jpeg");
                                        }
                                    }
                                }
                            }).show();
                        } else {
                            takePhoto(CAMERA_ORDER_PICTURE);
                        }
                    }

                }


                break;
            //场景照拍照
            case R.id.layout_takeScenePicture:
                if ("COMPLETED".equals(maintenanceBean.getWo_status_code())) {
                    if (maintenancePhotoBeanSceneList.size() == 0) {
                        Toast.makeText(this, "没有拍摄现场照片", Toast.LENGTH_SHORT).show();
                    } else {
                        Intent intent = new Intent(MainDetailActivity.this, DisplayScenePicturesActivity.class);
                        intent.putExtra("workorderid", workorderid);
                        intent.putExtra("wo_status_code", maintenanceBean.getWo_status_code());
                        startActivity(intent);
                    }
                } else {
                    if (maintenanceBean.getOrderCode() <= ORDER_ARRIVE) {
                        Toast.makeText(this, "未到现场，无法拍照", Toast.LENGTH_SHORT).show();
                    } else if (maintenanceBean.getOrderCode() >= ORDER_SUBMITINFORMATION) {
                        if (maintenancePhotoBeanSceneList.size() == 0) {
                            takePhoto(CAMERA_ACTION_PICTURE);
                        } else {
                            new AlertView("提示", null, "取消", null, new String[]{"拍照", "查看详情"}, this, AlertView.Style.ActionSheet, new OnItemClickListener() {
                                @Override
                                public void onItemClick(Object o, int position) {
                                    if (position == 0) {
                                        if (maintenancePhotoBeanSceneList.size() < 3) {
                                            takePhoto(CAMERA_ACTION_PICTURE);
                                        } else {
                                            Toast.makeText(MainDetailActivity.this, "最多拍摄3张场景照", Toast.LENGTH_SHORT).show();
                                        }
                                    } else if (position == 1) {
                                        Intent intent = new Intent(MainDetailActivity.this, DisplayScenePicturesActivity.class);
                                        intent.putExtra("workorderid", workorderid);
                                        startActivity(intent);
                                    }
                                }
                            }).show();
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 拍摄
     *
     * @param backType
     */
    private void takePhoto(int backType) {
        // 关闭手电
        CloseLight();
        photoName = UUID.randomUUID().toString();
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        File photo = new File(imgPath, photoName + ".jpeg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
        startActivityForResult(intent, backType);
    }

//    /**
//     * 显
//     *
//     * @param imageName
//     */
//    private void showPhoto(String imageName) {
//        File file = new File(imgPath + imageName + ".jpeg");
//        if (file.exists()) {
//            Intent intent = new Intent(Intent.ACTION_VIEW);
//            intent.setDataAndType(Uri.fromFile(file), "image/*");
//            try {
//                startActivity(intent);
//            } catch (Exception e) {
//                Toast.makeText(this, "无法查看大图", Toast.LENGTH_SHORT).show();
//            }
//        } else {
//            Toast.makeText(MainDetailActivity.this, "未获取到本地照片", Toast.LENGTH_SHORT).show();
//        }
//    }

    /**
     * 显
     *
     * @param imageFile
     */
    private void showPhoto(File imageFile) {
        if (imageFile.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
//            intent.setData(Uri.fromFile(imageFile));
            intent.setDataAndType(Uri.fromFile(imageFile), "image/*");
            try {
                startActivity(intent);
            } catch (Exception e) {
                Toast.makeText(this, "无法查看大图", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(MainDetailActivity.this, "未获取到本地照片", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示照片大图
     *
     * @param imagePath
     */
    private void showPhoto(String imagePath) {
        Intent intent = new Intent(MainDetailActivity.this, PhotoShowBigActivity.class);
//            intent.setData(Uri.fromFile(imageFile));
        intent.putExtra("ImagePath", imagePath);
        startActivity(intent);
    }

    /**
     * 提交按钮  事件处
     */
    private class SubmitAsyncTask extends AsyncTask<Void, Void, Void> {
        List<FndResource> resources;

        @Override
        protected Void doInBackground(Void... params) {
            if (maintenanceBean.getOrderCode() == ORDER_SUBMITINFORMATION || maintenanceBean.getOrderCode() == ORDER_SUBMIT_WITHOUT_IMAGE || maintenanceBean.getOrderCode() == ORDER_STATION_REJECT) {
                resources = getUnuploadImage();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
            if (maintenanceBean.getOrderCode() == ORDER_STARTOFF) {
                maintenanceBean.setOrderCode(ORDER_ARRIVE);
                maintenanceBean.setDeparture_date(Util.getSystemDateNow());
                maintenanceBean.setDeparture_latitude(la);
                maintenanceBean.setDeparture_longitude(lo);
                maintenanceBean.setIsDirty(1);
                maintenanceBean.update(maintenanceBean.getId());
                maintenanceBeanTemp.setOrderCode(ORDER_ARRIVE);
                maintenanceBeanTemp.setDeparture_date(Util.getSystemDateNow());
                maintenanceBeanTemp.setDeparture_latitude(la);
                maintenanceBeanTemp.setDeparture_longitude(lo);
                maintenanceBeanTemp.setIsDirty(1);
                maintenanceBeanTemp.update(maintenanceBean.getId());

                button_submit.setText("到达现场");
                departuredateTv.setText(maintenanceBean.getDeparture_date());
                departuredateTv.setTextColor(Color.parseColor("#666666"));
                new UpdateTimeAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            } else if (maintenanceBean.getOrderCode() == ORDER_ARRIVE) {
                Gps gps;
                if ("未成功获取".equals(la) || "未成功获取".equals(lo)) {
                    gps = new Gps(0, 0);
                } else {
                    gps = new Gps(Double.parseDouble(la), Double.parseDouble(lo));
                }
                onsiteSave(gps);
            } else if (maintenanceBean.getOrderCode() == ORDER_SUBMITINFORMATION || maintenanceBean.getOrderCode() == ORDER_SUBMIT_WITHOUT_IMAGE || maintenanceBean.getOrderCode() == ORDER_STATION_REJECT) {
                if (resources.size() > 0) {
                    uploadImage(resources);
                } else {
                    pd = new SVProgressHUD(MainDetailActivity.this);
                    // 提交数据
                    updateData();
                }

            }
            statusControl();
            super.onPostExecute(aVoid);
        }
    }

    /**
     * 上传时间
     */
    private class UpdateTimeAsyncTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            //上传工单数据
            int resultCode = MainControl.updateStatus(maintenanceBean, MainDetailActivity.this);
            return null;
        }
    }

    /**
     * 获取未上传
     *
     * @return
     */
    private ArrayList<FndResource> getUnuploadImage() {
        ArrayList<FndResource> resources = new ArrayList<FndResource>();
        List<MaintenancePhotoBean> maintenancePhotoBeanList = DataSupport.where("workorder_id = ? AND object_status_code = 'VALID'", workorderid).find(MaintenancePhotoBean.class);
        for (MaintenancePhotoBean maintenancePhotoBean : maintenancePhotoBeanList) {
            List<FndResource> fndResourceList = DataSupport.where("resourceId = ?", maintenancePhotoBean.getResource_id()).find(FndResource.class);
            if (null != fndResourceList && fndResourceList.size() > 0) {
                FndResource fndResource = fndResourceList.get(0);

                if (fndResource.getIsUpload() == 0) {
                    resources.add(fndResource);
                }
            }
        }
        for (MaintenancePhotoJobitemBean maintenancePhotoJobitemBean : maintenancePhotoJobitemBeanList) {
            if (!maintenancePhotoJobitemBean.getAction_type_result().equals("")) {
                List<FndResource> fndResourceList = DataSupport.where("resourceId = ?", maintenancePhotoJobitemBean.getAction_type_result()).find(FndResource.class);
                if (null != fndResourceList && fndResourceList.size() > 0) {
                    FndResource fndResource = fndResourceList.get(0);
                    if (fndResource.getIsUpload() == 0) {
                        resources.add(fndResource);
                    }
                }
            }
        }
        return resources;
    }

    /**
     * 上传照片
     **/
    private void uploadImage(List<FndResource> resources) {
        ResourceFacade resourceFacade = new ResourceFacade(
                MainDetailActivity.this);
        pd = new SVProgressHUD(MainDetailActivity.this);
        pd.showWithStatus("照片正在上传...");
        try {

            // 只传输该工单下的照片
            resourceFacade.startUploadFilesNew(resources);

        } catch (Exception e) {
            Log.e("", "~uploading img with exception:" + e.toString());
            Toast.makeText(MainDetailActivity.this, "上传照片失败", Toast.LENGTH_SHORT).show();
            if (pd.isShowing()) {
                pd.dismiss();
            }
        }
    }

    //单张照片上传完成
    @Subscribe
    public void onEventMainThread(EventCenter.SingleImageUploadSuccess event) {
        FndResource resource = event.getSuccessFndResource();
        FndResource fndResource = new FndResource();
        fndResource.setIsUpload(1);
        fndResource.update(resource.getId());
    }

    //全部照片上传完成
    @Subscribe
    public void onEventMainThread(EventCenter.AllImageUploadSuccess event) {

        // 提交数据
        Toast.makeText(this, "照片上传成功", Toast.LENGTH_SHORT).show();
        updateData();
    }

    //照片上传失败
    @Subscribe
    public void onEventMainThread(EventCenter.UploadImageFailed event) {
        Toast.makeText(MainDetailActivity.this, "上传照片失败", Toast.LENGTH_SHORT).show();
        if (pd.isShowing()) {
            pd.dismiss();
        }
    }

    /**
     * 更新
     */
    private void displayData() {

    }

    /**
     * 提交数据
     */
    private void updateData() {
//        pdData = new SVProgressHUD(MainDetailActivity.this);
        if (null == pd) {
            pd = new SVProgressHUD(MainDetailActivity.this);
        }
        pd.showWithStatus("数据正在上传，请稍后...");
        maintenanceBean.setWorkorder_description(editText_workorder_description.getText().toString());
        new UpdateDataAsyncTask()
                .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    /**
     * 数据上传
     */
    private class UpdateDataAsyncTask extends AsyncTask<Void, Void, Void> {

        int resultCode = 0;
        boolean notLocImage = false;

        @Override
        protected Void doInBackground(Void... params) {
            //执行流程
            int stepResult = MainControl.callBPMtoNextProcess(MainActivity.USERNAME, maintenanceBean.getProcess_id());
            Log.i("stepResult", "~~调用流程stepResult = " + stepResult);
            List<MaintenancePhotoBean> maintenancePhotoBeanList = DataSupport.where("workorder_id = ? AND object_status_code = 'VALID'", workorderid).find(MaintenancePhotoBean.class);
            //提交照片数据
            boolean isPhotosUpdate = MainControl.updateTakePhotos(maintenancePhotoBeanList, maintenancePhotoJobitemBeanList, MainActivity.USERNAME);

            if (isPhotosUpdate) {
                List<MaintenancePhotoBean> maintenancePhotoBeanList1 = new ArrayList<MaintenancePhotoBean>();
                maintenancePhotoBeanList1.addAll(DataSupport.where("workorder_id = ? AND object_status_code = 'VALID' AND item_type_code = 'WORKORDER_IMG'", workorderid).find(MaintenancePhotoBean.class));
                if (maintenancePhotoBeanList1.size() > 0) {
                    MaintenancePhotoBean maintenancePhotoBean = maintenancePhotoBeanList1.get(0);
                    FndResource fndResource = new FndResource();
                    try {
                        fndResource = DataSupport.where("resourceId = ?", maintenancePhotoBean.getResource_id()).find(FndResource.class).get(0);
                    } catch (Exception e) {
                        e.printStackTrace();
                        notLocImage = true;
                    }

                    if (fndResource.getIsUpload() == 1 || maintenanceBean.getOrderCode() == ORDER_STATION_REJECT || notLocImage) {
                        maintenanceBean.setWo_status_code("COMPLETED");
                        maintenanceBean.setOrderCode(ORDER_FINISH);
                        if ("".equals(maintenanceBean.getLeave_date())) {
                            maintenanceBean.setLeave_date(Util.getSystemDateNow());
                        }
                        maintenanceBean.setFinish_date(Util.getSystemDateNow());
                    } else {
                        maintenanceBean.setWo_status_code("SUBMITTED_WITHOUT_IMG");
                        if ("".equals(maintenanceBean.getLeave_date())) {
                            maintenanceBean.setLeave_date(Util.getSystemDateNow());
                        }
                        maintenanceBean.setOrderCode(ORDER_SUBMIT_WITHOUT_IMAGE);
                        maintenanceBean.setIsDirty(0);
                        maintenanceBean.update(maintenanceBean.getId());
                        MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
                        maintenanceBeanTemp.setWo_status_code("SUBMITTED_WITHOUT_IMG");
                        maintenanceBeanTemp.setOrderCode(ORDER_SUBMIT_WITHOUT_IMAGE);
                        maintenanceBeanTemp.setIsDirty(0);
                        maintenanceBeanTemp.update(maintenanceBean.getId());
                    }
                } else {
                    maintenanceBean.setWo_status_code("SUBMITTED_WITHOUT_IMG");
                    if ("".equals(maintenanceBean.getLeave_date())) {
                        maintenanceBean.setLeave_date(Util.getSystemDateNow());
                    }
                    maintenanceBean.setOrderCode(ORDER_SUBMIT_WITHOUT_IMAGE);
                    maintenanceBean.setIsDirty(0);
                    maintenanceBean.update(maintenanceBean.getId());
                    MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
                    maintenanceBeanTemp.setWo_status_code("SUBMITTED_WITHOUT_IMG");
                    maintenanceBeanTemp.setOrderCode(ORDER_SUBMIT_WITHOUT_IMAGE);
                    maintenanceBeanTemp.setIsDirty(0);
                    maintenanceBeanTemp.update(maintenanceBean.getId());
                }
                //上传工单数据
                resultCode = MainControl.updateStatus(maintenanceBean, MainDetailActivity.this);

                //上传电梯备忘
                ArrayList<MaintenanceMemoBean> maintenanceMemoBeanListTemp = new ArrayList<MaintenanceMemoBean>();
                maintenanceMemoBeanListTemp.addAll(DataSupport.where("ele_id = ? ", eleid).find(MaintenanceMemoBean.class));
                if (resultCode == INFO_SUCCEED && maintenanceMemoBeanListTemp.size() > 0) {
                    resultCode = MainControl.updateMemo(maintenanceMemoBeanListTemp);
                } else {
                    maintenanceBean.setWo_status_code("EXECUTE");
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            maintenanceBean = DataSupport.where("workorder_id = ?", workorderid).find(MaintenanceBean.class).get(0);
            if (resultCode == INFO_SUCCEED) {
                if ("COMPLETED".equals(maintenanceBean.getWo_status_code())) {
                    mntjobElv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                        @Override
                        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                            return false;
                        }
                    });
                    statusControl();

                } else if ("SUBMITTED_WITHOUT_IMG".equals(maintenanceBean.getWo_status_code())) {
                    button_submit.setText("照片补传");
                } else if ("STATION_REJECT".equals(maintenanceBean.getWo_status_code())) {
                    button_submit.setText("驳回重新提交");
                }
                Toast.makeText(MainDetailActivity.this, "上传数据成功", Toast.LENGTH_SHORT).show();
                maintenanceBean.setIsDirty(0);
                maintenanceBean.update(maintenanceBean.getId());
                MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
                maintenanceBeanTemp.setIsDirty(0);
                maintenanceBeanTemp.update(maintenanceBean.getId());

            } else {
                Toast.makeText(MainDetailActivity.this, "上传数据失败", Toast.LENGTH_SHORT).show();
            }
            if (null != pd && pd.isShowing()) {
                pd.dismiss();
            }

            super.onPostExecute(aVoid);
        }
    }

    //地图返回数据
    @Subscribe
    public void onEventMainThread(EventCenter.MapBack event) {
        final int position = event.getPosition();
        if (position == -1) {
            final Gps gps = event.getMapBack();

            try {
                Boolean isArrived = ServiceUtil.getCachelocation(MainDetailActivity.this, longitude + "", latitude + "");

                if (!isArrived) {
                    new AlertView("提示", "未到达电子围栏内，确认要到达？", "取消", new String[]{"确定"}, null, MainDetailActivity.this,
                            AlertView.Style.Alert, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int p) {
                            if (p == 0) {
                                onsiteSave(gps);
                            }
                        }
                    }).show();
                } else {
                    onsiteSave(gps);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    //删除场景照监听
    @Subscribe
    public void onEventMainThread(EventCenter.DeleteScenePhoto event) {
        maintenancePhotoBeanSceneList = (ArrayList<MaintenancePhotoBean>) DataSupport.where("workorder_id = ? AND object_status_code = 'VALID' AND item_type_code = 'ADDITIONAL_IMG'", workorderid).find(MaintenancePhotoBean.class);
        if (maintenancePhotoBeanSceneList.size() > 0) {
            textView_takeScenePicture.setText("已拍" + maintenancePhotoBeanSceneList.size() + "张");
        } else {
            textView_takeScenePicture.setText("未拍照片");
        }
    }

    /**
     * 到达 场数据处
     *
     * @param gps
     */
    private void onsiteSave(Gps gps) {
        maintenanceBean.setOnsite_date(Util.getSystemDateNow());
        maintenanceBean.setOrderCode(ORDER_SUBMITINFORMATION);
        maintenanceBean.setOnsite_longitude(gps.getWgLon() + "");
        maintenanceBean.setOnsite_latitude(gps.getWgLat() + "");
        maintenanceBean.setIsDirty(1);
        maintenanceBean.update(maintenanceBean.getId());
        MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
        maintenanceBeanTemp.setOnsite_date(Util.getSystemDateNow());
        maintenanceBeanTemp.setOrderCode(ORDER_SUBMITINFORMATION);
        maintenanceBeanTemp.setOnsite_longitude(gps.getWgLon() + "");
        maintenanceBeanTemp.setOnsite_latitude(gps.getWgLat() + "");
        maintenanceBeanTemp.setIsDirty(1);
        maintenanceBeanTemp.update(maintenanceBean.getId());
        button_submit.setText("离开并提交");
        onsitedateTv.setText(maintenanceBean.getOnsite_date());
        onsitedateTv.setTextColor(Color.parseColor("#666666"));
        displayBaffle();
        statusControl();
        new UpdateTimeAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    /**
     * 纹 听
     */
    private class MyOnRippleCompleteListener implements RippleView.OnRippleCompleteListener {

        @Override
        public void onComplete(RippleView rippleView) {
            switch (rippleView.getId()) {
                case R.id.rippleView_contract:
                    Intent intent1 = new Intent(MainDetailActivity.this, ContractElevatorInfoActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("maintenanceDetail", maintenanceDetailBean);
                    intent1.putExtras(bundle);
                    startActivity(intent1);
                    break;
                case R.id.rippleView_customer:
                    Intent intent2 = new Intent(MainDetailActivity.this, CustomerInfoActivity.class);
                    Bundle bundle2 = new Bundle();
                    bundle2.putSerializable("maintenanceDetail", maintenanceDetailBean);
                    intent2.putExtras(bundle2);
                    startActivity(intent2);
                    break;

                case R.id.rippleView_fastrepairhis:
                    Intent intent3 = new Intent(MainDetailActivity.this, FastrepairHistoryListActivity.class);
                    intent3.putExtra("ele_id", maintenanceDetailBean.getELE_ID());

                    startActivity(intent3);
                    break;

                case R.id.rippleView_remesNotice:
                    Intent intent4 = new Intent(MainDetailActivity.this, RemesNoticeListActivity.class);

                    startActivity(intent4);

                    break;

                case R.id.rippleView_history_problem:

                    Intent intent5 = new Intent(MainDetailActivity.this, RemesProblemHistoryActivity.class);
                    intent5.putExtra("workorder_id", workorderid);
                    startActivity(intent5);

                    break;

                default:
                    break;
            }
        }
    }


    /**
     * 初始化view
     */

    protected void initView() {
        ExitAppUtils.getInstance().addActivity(this);

        rl_title = (RelativeLayout)findViewById(R.id.rl_title);
//        PublicControl.setMargins(rl_title, 0, getStatusBarHeight(MainDetailActivity.this), 0, 0);

        EventBus.getDefault().register(this);//注册EventBus
        ConfigContext.newInstance(MainDetailActivity.this);
        maintenanceBean = (MaintenanceBean) getIntent().getSerializableExtra("MaintenanceBean");
        listPosition = getIntent().getIntExtra("position", -1);

        maintenancePhotoBeanSceneList = new ArrayList<MaintenancePhotoBean>();

        imageview_back = (ImageView) findViewById(R.id.imageview_back);
        rippleView_customer = (RippleView) findViewById(R.id.rippleView_customer);
        rippleView_customer.setRippleDuration(100);//设置水波时间

        rippleView_contract = (RippleView) findViewById(R.id.rippleView_contract);
        rippleView_contract.setRippleDuration(100);//设置水波时间

        rippleView_fastrepairhis = (RippleView) findViewById(R.id.rippleView_fastrepairhis);
        rippleView_fastrepairhis.setRippleDuration(100);//设置水波时间

        rippleView_remesNotice = (RippleView) findViewById(R.id.rippleView_remesNotice);
        rippleView_remesNotice.setRippleDuration(100);//设置水波时间

        rippleView_history_problem = (RippleView) findViewById(R.id.rippleView_history_problem);
        rippleView_history_problem.setRippleDuration(100);//设置水波时间

        workordernoTv = (TextView) findViewById(R.id.workordernoTv);
        buildingnameTv = (TextView) findViewById(R.id.buildingnameTv);
        locaddressTv = (TextView) findViewById(R.id.locaddressTv);
        customernameTv = (TextView) findViewById(R.id.customernameTv);
        elecontractnoTv = (TextView) findViewById(R.id.elecontractnoTv);
        staffnameTv = (TextView) findViewById(R.id.staffnameTv);
        mntschdateTv = (TextView) findViewById(R.id.mntschdateTv);
        departuredateTv = (TextView) findViewById(R.id.departuredateTv);
        onsitedateTv = (TextView) findViewById(R.id.onsitedateTv);
        mntjobtemplateTv = (TextView) findViewById(R.id.mntjobtemplateTv);
        mntjobElv = (MntjobExpandableListView) findViewById(R.id.mntjobElv);
        maintenancePhotoJobitemLv = (MainDetailListView) findViewById(R.id.maintenancePhotoJobitemLv);
        listView_memo = (MainDetailListView) findViewById(R.id.listView_memo);
        button_submit = (Button) findViewById(R.id.button_submit);
        textView_addMemo = (TextView) findViewById(R.id.textView_addMemo);
        editText_workorder_description = (EditText) findViewById(R.id.editText_workorder_description);
        textView_fastrepairHis = (TextView) findViewById(R.id.textView_fastrepairHis);
        layout_takeOrderPicture = (RelativeLayout) findViewById(R.id.layout_takeOrderPicture);
        layout_takeScenePicture = (RelativeLayout) findViewById(R.id.layout_takeScenePicture);
        imageView_takeOrderPicture = (ImageView) findViewById(R.id.imageView_takeOrderPicture);
        textView_takeScenePicture = (TextView) findViewById(R.id.textView_takeScenePicture);
        imageview_ele_remes = (ImageView) findViewById(R.id.imageview_ele_remes);
        imageView_light = (ImageView) findViewById(R.id.imageView_light);
        textView_addMemo.setOnClickListener(this);
        button_submit.setOnClickListener(this);
        imageview_back.setOnClickListener(this);
        layout_takeOrderPicture.setOnClickListener(this);
        layout_takeScenePicture.setOnClickListener(this);
        imageView_light.setOnClickListener(this);
        rippleView_customer.setOnRippleCompleteListener(new MyOnRippleCompleteListener());
        rippleView_contract.setOnRippleCompleteListener(new MyOnRippleCompleteListener());
        rippleView_fastrepairhis.setOnRippleCompleteListener(new MyOnRippleCompleteListener());
        rippleView_remesNotice.setOnRippleCompleteListener(new MyOnRippleCompleteListener());
        rippleView_history_problem.setOnRippleCompleteListener(new MyOnRippleCompleteListener());

        memoAdapter = new MemoAdapter(MainDetailActivity.this);
        listView_memo.setAdapter(memoAdapter);

        checkOrderCode();

        mntjobElv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                if (!maintenanceBean.getWo_status_code().equals("COMPLETED") && maintenanceBean.getOrderCode() > ORDER_ARRIVE) {
                    final String key = (String) parent.getExpandableListAdapter().getChild(groupPosition, childPosition);
                    new AlertView("提示", "确定要将“" + key + "”添加到备忘？", "取消", new String[]{"确定"}, null, MainDetailActivity.this,
                            AlertView.Style.Alert, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position == 0) {
                                MaintenanceMemoBean maintenanceMemoBean = new MaintenanceMemoBean();
                                maintenanceMemoBean.setEle_id(eleid);
                                maintenanceMemoBean.setEle_memo_id(UUID.randomUUID().toString());
                                maintenanceMemoBean.setEle_memo_description(key);
                                maintenanceMemoBean.setAssignee(MainActivity.USERNAME);
                                maintenanceMemoBean.save();
                                maintenanceMemoBeanList.add(maintenanceMemoBean);
                                memoAdapter.setList(maintenanceMemoBeanList, maintenanceBean.getOrderCode());
                            }
                        }
                    }).show();
                }
//                String info = map.get(key).get(childPosition);
                return false;
            }
        });

        statusControl();
        // 注册电量监听
        registerReceiver(batteryReceiver, new IntentFilter(
                Intent.ACTION_BATTERY_CHANGED));
    }

    /**
     *
     */
    private void checkOrderCode() {
        try {
            if (!"".equals(maintenanceBean.getDeparture_date())) {
                maintenanceBean.setOrderCode(ORDER_ARRIVE);
            }
            if (!"".equals(maintenanceBean.getOnsite_date())) {
                maintenanceBean.setOrderCode(ORDER_SUBMITINFORMATION);
            }
            if ("SUBMITTED_WITHOUT_IMG".equals(maintenanceBean.getWo_status_code())) {
                maintenanceBean.setOrderCode(ORDER_SUBMIT_WITHOUT_IMAGE);
            } else if ("STATION_REJECT".equals(maintenanceBean.getWo_status_code())) {
                maintenanceBean.setOrderCode(ORDER_STATION_REJECT);
            } else if (maintenanceBean.getWo_status_code().equals("COMPLETED")) {
                maintenanceBean.setOrderCode(ORDER_FINISH);
            }
        } catch (Exception e) {
            e.printStackTrace();
            maintenanceBean.setOrderCode(ORDER_STARTOFF);
        }
    }

    /**
     * 面控制
     */
    private void statusControl() {
        if (maintenanceBean.getOrderCode() <= ORDER_ARRIVE) {

            textView_addMemo.setEnabled(false);
//            layout_takeOrderPicture.setClickable(false);
//            layout_takeScenePicture.setClickable(false);
            editText_workorder_description.setEnabled(false);
        } else if (maintenanceBean.getOrderCode() >= ORDER_SUBMITINFORMATION) {
            textView_addMemo.setEnabled(true);
//            layout_takeOrderPicture.setClickable(true);
//            layout_takeScenePicture.setClickable(true);
            editText_workorder_description.setEnabled(true);
            memoAdapter.setList(maintenanceMemoBeanList, maintenanceBean.getOrderCode());
        }
        if (maintenanceBean.getWo_status_code().equals("COMPLETED")) {
            button_submit.setVisibility(View.GONE);
            textView_addMemo.setEnabled(false);
            editText_workorder_description.setEnabled(false);
            memoAdapter.setList(maintenanceMemoBeanList, maintenanceBean.getOrderCode());
        }
    }

    /**
     * 弹出挡板
     */
    public void displayBaffle() {
        View view = getLayoutInflater().inflate(R.layout.dialog_put_baffle, null);

        dialog = new AlertDialog.Builder(MainDetailActivity.this)
                .setTitle("放置挡板并拍照").setView(view)
                .setCancelable(false).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

            @Override
            public boolean onKey(DialogInterface dialog,
                                 int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getRepeatCount() == 0) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        ImageView imageView_takePhoto = (ImageView) view
                .findViewById(R.id.imageView_takePhoto);
        imageView_takePhoto
                .setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent,
                                CAMERA_DANGBAN);
                    }
                });
        dialog.show();
    }

    private void CloseLight() {
        if (mycamera != null) {
            mycamera.stopPreview();
            mycamera.release();
            mycamera = null;
            imageView_light.setImageResource(R.mipmap.maint_light_off);
        }

    }

    @SuppressWarnings("rawtypes")
    private void OpenLight() {
        Camera.Parameters params = mycamera.getParameters();
        List supportedList = params.getSupportedFlashModes();
        if (level < 15) {
            Toast.makeText(MainDetailActivity.this, "当前电量低于15%，手电筒可能无法使用",
                    Toast.LENGTH_LONG).show();
        }
        if (null != supportedList) {
            params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            mycamera.setParameters(params);
            mycamera.startPreview();
            imageView_light.setImageResource(R.mipmap.maint_light_on);
        } else {
            Toast toast = Toast.makeText(getApplicationContext(),
                    "没有闪光灯无法使用手电筒！", Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            mycamera.release();
            mycamera = null;
        }
    }

    /**
     * 获取手机当前 量
     */
    private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            level = intent.getIntExtra("level", 0); // level加%就是当前电量了
        }
    };

    private void registerReceiver() {

        jumpingBeans = JumpingBeans.with(mntjobtemplateTv)
                .appendJumpingDots()
                .build();

        IntentFilter filter = new IntentFilter();
        filter.addAction(MNTJOBSERVICE_RESULT);
        registerReceiver(mntjobReceiver, filter);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.remes_act_maindetail);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mntjobReceiver);
        unregisterReceiver(batteryReceiver);
        EventBus.getDefault().post(new EventCenter.UpdateOneRow(maintenanceBean, listPosition));
        // 消息bus解注
        EventBus.getDefault().unregister(this);
        if (null != mycamera) {
            CloseLight();
        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }

    @Override
    public void onBackPressed() {
//        scrollToFinishActivity();
        finish();
    }


}
